package com.example.util;

import cn.afterturn.easypoi.entity.ImageEntity;
import cn.afterturn.easypoi.excel.annotation.ExcelEntity;
import cn.afterturn.easypoi.excel.entity.params.ExcelBaseEntity;
import cn.hutool.poi.word.Word07Writer;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.documents.OleLinkType;
import com.spire.doc.documents.OleObjectType;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.fields.DocPicture;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtils;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.StandardChartTheme;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.labels.ItemLabelAnchor;
import org.jfree.chart.labels.ItemLabelPosition;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.category.StackedBarRenderer;
import org.jfree.chart.renderer.category.StandardBarPainter;
import org.jfree.chart.ui.RectangleEdge;
import org.jfree.chart.ui.TextAnchor;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;
import org.springframework.util.Assert;
import sun.misc.BASE64Encoder;

import java.awt.*;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class JfreeUtil {

    private static String tempImgPath="D:\\tempJfree.jpeg";

    public static ImageEntity pieChart(String title, Map<String, Integer> datas, int width, int height) {

        //创建主题样式
        StandardChartTheme standardChartTheme = new StandardChartTheme("CN");
        //设置标题字体
        standardChartTheme.setExtraLargeFont(new Font("宋体", Font.BOLD, 20));
        //设置图例的字体
        standardChartTheme.setRegularFont(new Font("宋体", Font.PLAIN, 15));
        //设置轴向的字体
        standardChartTheme.setLargeFont(new Font("宋体", Font.PLAIN, 15));
        //设置主题样式
        ChartFactory.setChartTheme(standardChartTheme);

        //根据jfree生成一个本地饼状图
        DefaultPieDataset pds = new DefaultPieDataset();
        datas.forEach(pds::setValue);
        //图标标题、数据集合、是否显示图例标识、是否显示tooltips、是否支持超链接
        JFreeChart chart = ChartFactory.createPieChart(title, pds, true, false, false);
        //设置抗锯齿
        chart.setTextAntiAlias(false);
        PiePlot plot = (PiePlot) chart.getPlot();
        plot.setNoDataMessage("暂无数据");
        //忽略无值的分类
        plot.setIgnoreNullValues(true);
        plot.setBackgroundAlpha(0f);
        //设置标签阴影颜色
        plot.setShadowPaint(new Color(255,255,255));
        //设置标签生成器(默认{0})
        plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0}({1})/{2}"));
        try {
            ChartUtils.saveChartAsJPEG(new File(tempImgPath), chart, width, height);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        ImageEntity imageEntity = new ImageEntity(imgToByte(), width, height);
        Assert.notNull(imageEntity.getData(),"生成饼状图对象失败！");
        return imageEntity;
    }


    public static ImageEntity lineChart(String title, Map<String, Integer> datas, int width, int height) {

        //创建主题样式
        StandardChartTheme standardChartTheme = new StandardChartTheme("CN");
        //设置标题字体
        standardChartTheme.setExtraLargeFont(new Font("宋体", Font.BOLD, 20));
        //设置图例的字体
        standardChartTheme.setRegularFont(new Font("宋体", Font.PLAIN, 15));
        //设置轴向的字体
        standardChartTheme.setLargeFont(new Font("宋体", Font.PLAIN, 15));
        //设置主题样式
        ChartFactory.setChartTheme(standardChartTheme);

        //根据jfree生成一个本地柱状图
        DefaultCategoryDataset pds = new DefaultCategoryDataset();
        pds.addValue(440, "数据1", "类型1"); //封数据
        pds.addValue(540, "数据2", "类型1"); //封数据
        pds.addValue(340, "数据1", "类型2"); //封数据
        pds.addValue(440, "数据2", "类型2"); //封数据
        pds.addValue(240, "数据1", "类型3"); //封数据
        pds.addValue(540, "数据2", "类型3"); //封数据
        //图标标题、数据集合、是否显示图例标识、是否显示tooltips、是否支持超链接

        JFreeChart chart = ChartFactory.createStackedBarChart("统计图标题",
                "测试", // domain axis label
                "数量", // range axis label
                pds, // data
                PlotOrientation.VERTICAL, // 图标方向
                true, // 是否显示legend
                true, // 是否显示tooltips
                false // 是否显示URLs
        );
        chart.getLegend().setPosition(RectangleEdge.TOP);
        //设置抗锯齿
        chart.setTextAntiAlias(false);
        CategoryPlot plot = (CategoryPlot) chart.getPlot();
        plot.setNoDataMessage("暂无数据");
        //忽略无值的分类
//        plot.setIgnoreNullValues(true);
        plot.setBackgroundAlpha(0f);
//        plot.setDomainGridlinePaint(Color.blue);
        plot.setDomainGridlinesVisible(true);
//        //设置网格横线颜色
        plot.setRangeGridlinePaint(Color.blue);
        plot.setRangeGridlinesVisible(true);
//        //图片背景色
        plot.setBackgroundPaint(Color.LIGHT_GRAY);
        plot.setOutlineVisible(true);
//        //图边框颜色
//        plot.setOutlinePaint(Color.magenta);
        //设置标签阴影颜色
//        //设置标签生成器(默认{0})
//        plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0}({1})/{2}"));

        BarRenderer  renderer = new BarRenderer();
        renderer.setBarPainter(new StandardBarPainter());
        renderer.setDefaultItemLabelsVisible(true);
        renderer.setDefaultItemLabelGenerator(new StandardCategoryItemLabelGenerator());
        // 设置最高的一个 Item 与图片顶端的距离
        ValueAxis rangeAxis = plot.getRangeAxis();
        rangeAxis.setUpperMargin(0.15);
        plot.setRangeAxis(rangeAxis);

        renderer.setDefaultPaint(Color.BLACK);//设置柱的字体颜色
        renderer.setSeriesPaint(0,Color.ORANGE); //设置柱的颜色
        renderer.setItemLabelAnchorOffset(0);
        //搭配ItemLabelAnchor TextAnchor 这两项能达到不同的效果，但是ItemLabelAnchor最好选OUTSIDE，因为INSIDE显示不出来
        renderer.setDefaultPositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE1, TextAnchor.BASELINE_CENTER));
        renderer.setMaximumBarWidth(0.08); //设置柱子宽度
        renderer.setMinimumBarLength(0.1); //设置柱子高度
        // 设置每个地区所包含的平行柱的之间距离
//        renderer.setItemMargin(0);
        plot.setForegroundAlpha(0.65f);
        plot.setRenderer(renderer);
        try {
            ChartUtils.saveChartAsJPEG(new File(tempImgPath), chart, width, height);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        ImageEntity imageEntity = new ImageEntity(imgToByte(), width, height);

        Assert.notNull(imageEntity.getData(),"生成饼状图对象失败！");
        return imageEntity;
    }


    /**
     * 将图片转化为字节数组
     * @return 字节数组
     */
    private static byte[] imgToByte(){
        File file = new File(tempImgPath);
        byte[] buffer = null;
        try {
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //删除临时文件
        file.delete();
        return buffer;
    }


    /**
     * 将图片转化为字节数组
     * @return 字节数组
     */
    private static byte[] fileToByte(String path){
        File file = new File(path);
        byte[] buffer = null;
        try {
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }

    public static void main(String[] args) {
        Map<String, Object> map = new HashMap<>(4);
        //模拟饼状图数据
        Map<String, Integer> datas = new HashMap<>(3);
        datas.put("一号",10);
        datas.put("二号",20);
        datas.put("三号",40);
//        ImageEntity imageEntity = JfreeUtil.pieChart("测试",datas, 500, 300);
//        ImageEntity imageEntity = JfreeUtil.lineChart("测试",datas, 550, 300);
//        map.put("p", imageEntity);

        test();

//        FtlWordUtil.exportWord("C:\\Users\\Administrator\\Desktop\\测试模板.docx", "D:/", "生成文件.docx", map);

//        FtlWordUtil.exportWord("C:\\Users\\Administrator\\Desktop\\生成文件.docx", "D:/", "生成文件1.docx", map);

    }


    public static void test(){
        Document doc = new Document();
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\测试模板.docx");

        //获取最后一节
        Section section = doc.getLastSection();

        //添加段落
        Paragraph par = section.addParagraph();

        //加载一个图片，它将作为外部文件的符号显示在Word文档中
        DocPicture pdfIcon = new DocPicture(doc);
        pdfIcon.loadImage("C:\\Users\\Administrator\\Desktop\\图标.png");

        //将一个PDF文件作为OLE对象插入Word文档
//        par.appendOleObject("C:\\Users\\Administrator\\Desktop\\123123.xlsx", pdfIcon, OleObjectType.Excel_97_2003_Worksheet);
        par.appendOleObject(fileToByte("C:\\Users\\Administrator\\Desktop\\123123.xlsx"),pdfIcon, OleObjectType.Open_Document_Spreadsheet);
        // 得到文件 之后转成beye 然后使用base64转码


        //另存为一个文档
        doc.saveToFile("C:\\Users\\Administrator\\Desktop\\EmbedDocument.docx", FileFormat.Docx_2013);
    }

}
